//
//  SlideInTransitioningDelegate.swift
//  SCA
//
//  Created by tjun on 2025/9/14.
//

import UIKit

class SlideInAnimator: NSObject, UIViewControllerAnimatedTransitioning {
    let isPresenting: Bool
    let duration: TimeInterval = 0.35
    
    init(isPresenting: Bool) {
        self.isPresenting = isPresenting
        super.init()
    }
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return duration
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let containerView = transitionContext.containerView
        
        if isPresenting {
            // 目标控制器
            guard let toView = transitionContext.view(forKey: .to) else { return }
            let finalFrame = transitionContext.finalFrame(for: transitionContext.viewController(forKey: .to)!)
            
            // 初始位置：屏幕左侧，透明
            toView.frame = finalFrame.offsetBy(dx: -finalFrame.width, dy: 0)
            toView.alpha = 0.0
            containerView.addSubview(toView)
            
            UIView.animate(withDuration: duration, animations: {
                toView.frame = finalFrame
                toView.alpha = 1.0
            }, completion: { finished in
                transitionContext.completeTransition(finished)
            })
            
        } else {
            // dismiss 时
            guard let fromView = transitionContext.view(forKey: .from) else { return }
            let initialFrame = fromView.frame
            
            UIView.animate(withDuration: duration, animations: {
                // 向左滑出并渐隐
                fromView.frame = initialFrame.offsetBy(dx: -initialFrame.width, dy: 0)
                fromView.alpha = 0.0
            }, completion: { finished in
                fromView.removeFromSuperview()
                transitionContext.completeTransition(finished)
            })
        }
    }
}


class SlideInTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController,
                             presenting: UIViewController,
                             source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return SlideInAnimator(isPresenting: true)
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return SlideInAnimator(isPresenting: false)
    }
}
